package p.ithorns.sample.spel;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanExpressionResolver;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.expression.StandardBeanExpressionResolver;

/**
 * SpelBeanFactoryPostProcessor
 * 替换默认模版(#{})
 * 使用BeanFactoryPostProcessor接口提供postProcessBeanFactory回调方法，
 * 它是在IoC容器创建好但还未进行任何Bean初始化时被ApplicationContext实现调用，
 * 因此在这个阶段把SpEL前缀及后缀修改掉是安全的
 *
 * @author Ht.L
 * @date 2024-12-26 21:36
 * @since 1.0.0
 */
//@Component
public class SpelBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        BeanExpressionResolver beanExpressionResolver = beanFactory.getBeanExpressionResolver();
        if (beanExpressionResolver instanceof StandardBeanExpressionResolver) {
            StandardBeanExpressionResolver resolver = (StandardBeanExpressionResolver) beanExpressionResolver;
            resolver.setExpressionPrefix("%{");
            resolver.setExpressionSuffix("}");
        }
    }
}